<?php

class Academico_LoginController extends Zend_Controller_Action {

    private $_debugLogger;
    private $_errorLogger;

    public function init() {
        $this->_helper->layout->disableLayout();
        $this->_debugLogger = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
        $this->_errorLogger = Zend_Registry::get(VirtualLabs_Common::ERROR_LOG);
    }

    public function indexAction() {
        
    }

    public function generateAction() {
        $password = $this->getRequest()->getParam("generate");
        echo md5($password);
    }

    public function passwordforgotAction() {

        if ($this->getRequest()->isPost()) {
            $userDao = new VirtualLabs_Admin_Usuario();
            $user = $userDao->getUsuario(array('nombre', 'apellido', 'username'), array('email' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('email'))));
            $this->_debugLogger->debug('[user] : ' . print_r($user, true));
            if ($user) {
                $generatedPassword = $userDao->generatePassword();
                $this->_debugLogger->debug('[generatedPassword] : ' . $generatedPassword);
                if ($generatedPassword) {
                    $config = array('auth' => 'login',
                        'port' => '26',
                        'username' => 'support@pearljamparaguay.com',
                        'password' => 'AwWmJc]U))UF');
                    $tr = new Zend_Mail_Transport_Smtp('mail.pearljamparaguay.com', $config);
                    Zend_Mail::setDefaultTransport($tr);
                    Zend_Mail::setDefaultFrom('support@pearljamparaguay.com', 'Soporte Virtual Labs Manager');
                    Zend_Mail::setDefaultReplyTo('support@pearljamparaguay.com', 'Soporte Virtual Labs Manager');
                    $mail = new Zend_Mail();
                    $mail->addTo($this->getRequest()->getParam('email'));
                    $this->_debugLogger->debug('[email] : ' . $this->getRequest()->getParam('email'));
                    $mail->setSubject('Solicitud de cambio de password');
                    $msg = utf8_encode("Estimado/a " . $user["nombre"] . ": <br><br>Clic <a href='" .
                            $this->view->baseUrl() . "/academico/login/resetpassword/password/" .
                            $generatedPassword .
                            "/username/" . $user['username'] . "'>aquí</a> para completar el proceso de reinicio de contraseña. <br>"
                            . "Si el enlace no funciona, utilice estos datos para ingresar:
                                        <ul><li>username : {$user['username']}</li><li>password: {$generatedPassword}</li></ul><br><br>Saludos!");
                    $mail->setBodyHtml($msg);
                    $mail->send($tr);
                    $this->view->changeError = "<div class='alert alert-block alert-success fade in' id='value-alert'>Password restablecido. Favor verificar su correo!</div>";
                    $this->_forward('index');
                } else {
                    $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Contacte con el administrador!</div>";
                }
            }
        }
    }

    public function logoutAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        Zend_Auth::getInstance()->clearIdentity();
        $this->_forward("index", "login", "academico");
    }

    public function loginAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        if (Zend_Auth::getInstance()->hasIdentity()) {
            $this->_forward("index", "laboratorioalumno", "academico");
        }

        $login = new VirtualLabs_Login();
        try {
            if ($login->doLogin($this->getRequest()->getParam('username'), $this->getRequest()->getParam('password'))) {
                $this->_forward("index", "laboratorioalumno", "academico");
            } else {
                $this->view->loginError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Verifique el nombre de usuario y password!</div>";
                $this->_forward("index");
            }
        } catch (Exception $e) {
            $this->_errorLogger->err($e->getMessage());
            $this->_errorLogger->err($e->getTraceAsString());
            $this->view->loginError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Verifique el nombre de usuario y password!</div>";
            $this->_forward("index");
        }
    }

    public function resetpasswordAction() {
        $userDao = new VirtualLabs_Admin_Usuario();
        try {
            $userDao->resetPassword($this->getRequest()->getParam('username'), $this->getRequest()->getParam('password'));
            $this->_forward('index', 'laboratorioalumno', 'academico');
        } catch (Exception $e) {
            throw $e;
        }
    }

    public function loginforgotAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $key = $this->getRequest()->getParam("key");
        $this->_debugLogger->debug('loginforgot action..');
        $this->_debugLogger->debug('[key] : ' . $key);
        $login = new VirtualLabs_Login();
        if (isset($key)) {
            if (strlen(trim($key)) > 0) {
                $this->view->changeError = $login->loginForgot($key);
            } else {
                $this->view->changeError = "<div class='alert alert-block alert-error fade in' id='value-alert'>Verificar su correo!</div>";
            }
        }
    }

}

